#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2025/3/31 15:24
# @Author  : 梁满仓
# @File    : breaking_through_ma7_of_600519.py
# @Software: PyCharm

import akshare as ak
import pandas as pd


def get_all_ma7_breakthroughs(stock_code, start_date='20240101', end_date='20241231'):
    """
    获取股票所有突破7日均线并且第二日站稳7日均线的时间和收盘价

    参数:
        stock_code: 股票代码，例如 '600519' (贵州茅台)
        start_date: 开始日期，默认为 '2022-01-01'
        end_date: 结束日期，默认为 '2024-12-31'

    返回:
        DataFrame，包含所有突破记录，如果没有找到则返回空DataFrame
    """
    # 获取股票历史数据
    try:
        stock_df = ak.stock_zh_a_hist(symbol=stock_code, period="daily", start_date=start_date, end_date=end_date, adjust="hfq")
    except Exception as e:
        print(f"获取股票数据失败: {e}")
        return pd.DataFrame()

    # 确保数据按日期升序排列
    stock_df = stock_df.sort_values('日期').reset_index(drop=True)

    # 计算7日均线
    stock_df['MA7'] = stock_df['收盘'].rolling(window=7, min_periods=1).mean()

    # 初始化结果列表
    results = []

    # 找出所有突破和站稳的点
    for i in range(1, len(stock_df) - 1):  # 留出一天用于确认
        # 前一天收盘价低于7日均线，当天收盘价高于7日均线 - 突破
        prev_close = stock_df.at[i - 1, '收盘']
        prev_ma7 = stock_df.at[i - 1, 'MA7']
        current_close = stock_df.at[i, '收盘']
        current_ma7 = stock_df.at[i, 'MA7']

        if prev_close < prev_ma7 and current_close > current_ma7:
            # 检查第二天是否站稳 (收盘价仍在7日均线之上)
            next_close = stock_df.at[i + 1, '收盘']
            next_ma7 = stock_df.at[i + 1, 'MA7']

            if next_close > next_ma7:
                # 记录满足条件的记录
                results.append({
                    '突破日期': stock_df.at[i, '日期'],
                    '突破收盘价': current_close,
                    '突破日MA7': current_ma7,
                    '确认日期': stock_df.at[i + 1, '日期'],
                    '确认收盘价': next_close,
                    '确认日MA7': next_ma7,
                    '突破幅度(%)': round((current_close - current_ma7) / current_ma7 * 100, 2),
                    '确认幅度(%)': round((next_close - next_ma7) / next_ma7 * 100, 2)
                })

    # 转换为DataFrame
    result_df = pd.DataFrame(results)

    if result_df.empty:
        print(f"股票 {stock_code} 在指定时间范围内未找到任何突破7日均线并站稳的记录")
    else:
        print(f"股票 {stock_code} 共找到 {len(result_df)} 次突破7日均线并站稳的记录")

    return result_df


# 示例使用
if __name__ == "__main__":
    stock_code = '600519'  # 贵州茅台
    breakthroughs = get_all_ma7_breakthroughs(stock_code)

    if not breakthroughs.empty:
        # 打印所有突破记录
        pd.set_option('display.max_columns', None)
        pd.set_option('display.expand_frame_repr', False)
        print(breakthroughs)

        # 保存到Excel文件
        breakthroughs.to_excel(f"{stock_code}_7日均线突破记录.xlsx", index=False)
        print(f"结果已保存到 {stock_code}_7日均线突破记录.xlsx")